package com.iot.manager.data.repository;

import android.content.Context;
import com.iot.manager.data.cache.DeviceDataCache;
import com.iot.manager.data.models.DeviceData;
import com.iot.manager.network.ApiService;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class DeviceDataRepository {
    private final ApiService apiService;
    private final DeviceDataCache cache;
    private final String deviceId;
    private static final int MAX_RETRY_COUNT = 3;

    public DeviceDataRepository(Context context, ApiService apiService, String deviceId) {
        this.apiService = apiService;
        this.cache = new DeviceDataCache(context);
        this.deviceId = deviceId;
    }

    public interface DataCallback {
        void onSuccess(List<DeviceData> data);
        void onError(String error);
        void onLoading(boolean isLoading);
    }

    public void getDeviceData(DataCallback callback) {
        // 检查缓存
        if (cache.isCacheValid(deviceId)) {
            List<DeviceData> cachedData = cache.getData(deviceId);
            if (!cachedData.isEmpty()) {
                callback.onSuccess(cachedData);
                // 后台刷新数据
                refreshData(callback, false);
                return;
            }
        }

        // 没有有效缓存，从网络加载
        refreshData(callback, true);
    }

    private void refreshData(DataCallback callback, boolean showLoading) {
        if (showLoading) {
            callback.onLoading(true);
        }

        // 获取当前时间
        Date now = new Date();
        // 获取24小时前的时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date yesterday = calendar.getTime();

        apiService.getDeviceData(deviceId, yesterday, now).enqueue(new Callback<List<DeviceData>>() {
            @Override
            public void onResponse(Call<List<DeviceData>> call, Response<List<DeviceData>> response) {
                if (showLoading) {
                    callback.onLoading(false);
                }

                if (response.isSuccessful() && response.body() != null) {
                    List<DeviceData> data = response.body();
                    // 保存到缓存
                    cache.saveData(deviceId, data);
                    callback.onSuccess(data);
                } else {
                    handleError(callback, "获取数据失败: " + response.code());
                }
            }

            @Override
            public void onFailure(Call<List<DeviceData>> call, Throwable t) {
                if (showLoading) {
                    callback.onLoading(false);
                }
                handleError(callback, "网络请求失败: " + t.getMessage());
            }
        });
    }

    private void handleError(DataCallback callback, String error) {
        // 如果有缓存数据，显示缓存数据
        List<DeviceData> cachedData = cache.getData(deviceId);
        if (!cachedData.isEmpty()) {
            callback.onSuccess(cachedData);
            callback.onError("使用缓存数据: " + error);
        } else {
            callback.onError(error);
        }
    }

    public void clearCache() {
        cache.clearCache(deviceId);
    }
} 